import 'dart:convert';

/// 活动数据模型
class ActivityData {
  final int activityId;
  final String activityTitle;
  final List<String> activityImages;
  final List<String> activityType;
  final List<String> activityTags;
  final String activityDetails;
  final String activityLocation;
  final double longitude;
  final double latitude;
  final String activityPublishTime;
  final List<String> activityCategory;
  final List<String> activityRestriction;
  final int activityCurrentParticipants;
  final int activityMaxParticipants;
  final int publisherId;
  final String publisherAvatar;
  final String publisherNickname;
  final String publisherSignature;
  final String publisherGender;  // 🎯 添加发布者性别字段
  final List<String> publisherTags;
  final List<String> activityStatus;
  final List<String> status;
  final Map<String, dynamic>? extraData;
  final double? distance;
  final int? minutesAgo;
  final double? weightScore;

  ActivityData({
    required this.activityId,
    required this.activityTitle,
    required this.activityImages,
    required this.activityType,
    required this.activityTags,
    required this.activityDetails,
    required this.activityLocation,
    required this.longitude,
    required this.latitude,
    required this.activityPublishTime,
    required this.activityCategory,
    required this.activityRestriction,
    required this.activityCurrentParticipants,
    required this.activityMaxParticipants,
    required this.publisherId,
    required this.publisherAvatar,
    required this.publisherNickname,
    required this.publisherSignature,
    required this.publisherGender,  // 🎯 添加发布者性别字段
    required this.publisherTags,
    required this.activityStatus,
    required this.status,
    this.extraData,
    this.distance,
    this.minutesAgo,
    this.weightScore,
  });

  /// 从JSON创建实例
  factory ActivityData.fromJson(Map<String, dynamic> json) {
    return ActivityData(
      activityId: json['activityId'] ?? 0,
      activityTitle: json['activityTitle'] ?? '',
      activityImages: _parseStringList(json['activityImages']),
      activityType: _parseStringList(json['activityType']),
      activityTags: _parseStringList(json['activityTags']),
      activityDetails: json['activityDetails'] ?? '',
      activityLocation: json['activityLocation'] ?? '',
      longitude: (json['longitude'] as num?)?.toDouble() ?? 0.0,
      latitude: (json['latitude'] as num?)?.toDouble() ?? 0.0,
      activityPublishTime: json['activityPublishTime'] ?? '',
      activityCategory: _parseStringList(json['activityCategory']),
      activityRestriction: _parseStringList(json['activityRestriction']),
      activityCurrentParticipants: json['activityCurrentParticipants'] ?? 0,
      activityMaxParticipants: json['activityMaxParticipants'] ?? 0,
      publisherId: json['publisherId'] ?? 0,
      publisherAvatar: json['publisherAvatar'] ?? '',
      publisherNickname: json['publisherNickname'] ?? '',
      publisherSignature: json['publisherSignature'] ?? '',
      publisherGender: json['publisherGender'] ?? '',  // 🎯 解析发布者性别
      publisherTags: _parseStringList(json['publisherTags']),
      activityStatus: _parseStringList(json['activityStatus']),
      status: _parseStringList(json['status']),
      extraData: json['extraData'] is Map<String, dynamic> 
          ? json['extraData'] 
          : null,
      distance: (json['distance'] as num?)?.toDouble(),
      minutesAgo: json['minutes_ago'],
      weightScore: (json['weight_score'] as num?)?.toDouble(),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'activityId': activityId,
      'activityTitle': activityTitle,
      'activityImages': activityImages,
      'activityType': activityType,
      'activityTags': activityTags,
      'activityDetails': activityDetails,
      'activityLocation': activityLocation,
      'longitude': longitude,
      'latitude': latitude,
      'activityPublishTime': activityPublishTime,
      'activityCategory': activityCategory,
      'activityRestriction': activityRestriction,
      'activityCurrentParticipants': activityCurrentParticipants,
      'activityMaxParticipants': activityMaxParticipants,
      'publisherId': publisherId,
      'publisherAvatar': publisherAvatar,
      'publisherNickname': publisherNickname,
      'publisherSignature': publisherSignature,
      'publisherGender': publisherGender,  // 🎯 序列化发布者性别
      'publisherTags': publisherTags,
      'activityStatus': activityStatus,
      'status': status,
      if (extraData != null) 'extraData': extraData,
      if (distance != null) 'distance': distance,
      if (minutesAgo != null) 'minutes_ago': minutesAgo,
      if (weightScore != null) 'weight_score': weightScore,
    };
  }

  /// 解析字符串列表，处理各种数据格式（包括null值）
  static List<String> _parseStringList(dynamic data) {
    if (data == null) return [];
    
    try {
      if (data is List) {
        // 过滤掉null值，并将其他值转换为字符串
        return data
            .where((item) => item != null)  // 过滤null值
            .map((item) => item.toString())
            .where((str) => str.isNotEmpty && str != 'null')  // 过滤空字符串和'null'字符串
            .toList();
      } else if (data is String) {
        // 尝试解析JSON字符串
        if (data.startsWith('[') && data.endsWith(']')) {
          try {
            var decoded = json.decode(data);
            if (decoded is List) {
              return decoded
                  .where((item) => item != null)  // 过滤null值
                  .map((item) => item.toString())
                  .where((str) => str.isNotEmpty && str != 'null')  // 过滤空字符串和'null'字符串
                  .toList();
            }
          } catch (e) {
            // 如果解析失败，返回原字符串作为单个元素（如果不为空）
            if (data.isNotEmpty && data != 'null') {
              return [data];
            }
          }
        } else if (data.isNotEmpty && data != 'null') {
          return [data];
        }
      }
    } catch (e) {
      print('解析字符串列表出错: $e, data: $data');
    }
    
    return [];
  }

  /// 获取距离描述
  String get distanceDescription {
    if (distance == null) return '未知距离';
    if (distance! < 1) {
      return '${(distance! * 1000).toInt()}米';
    }
    return '${distance!.toStringAsFixed(1)}公里';
  }

  /// 获取发布时间描述
  String get timeAgoDescription {
    if (minutesAgo == null) return '未知时间';
    
    if (minutesAgo! < 60) {
      return '${minutesAgo}分钟前';
    } else if (minutesAgo! < 1440) {
      return '${(minutesAgo! / 60).floor()}小时前';
    } else {
      return '${(minutesAgo! / 1440).floor()}天前';
    }
  }

  /// 判断活动是否正在进行
  bool get isActive {
    return activityStatus.contains('进行中') && status.contains('开启');
  }

  /// 判断活动是否已满员
  bool get isFull {
    return activityCurrentParticipants >= activityMaxParticipants;
  }

  /// 获取参与者信息描述
  String get participantDescription {
    return '$activityCurrentParticipants/$activityMaxParticipants人';
  }

  @override
  String toString() {
    return 'ActivityData{activityId: $activityId, activityTitle: $activityTitle, distance: $distance, minutesAgo: $minutesAgo}';
  }
}
